package tom.reactor.websocket.config;

import com.google.common.collect.Maps;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.web.reactive.HandlerMapping;
import org.springframework.web.reactive.handler.SimpleUrlHandlerMapping;
import org.springframework.web.reactive.socket.WebSocketHandler;
import org.springframework.web.reactive.socket.server.support.WebSocketHandlerAdapter;
import tom.reactor.websocket.handler.DateTimeHandler;
import tom.reactor.websocket.handler.EchoHandler;
import tom.reactor.websocket.handler.UserHandler;

import java.util.Map;

/**
 * webSocket注册到WebFlux
 * @author ZHUFEIFEI
 */
@Configuration
public class WebSocketConfig {

    /**
     * 负责把webSocket关联到WebFlux
     * @return
     */
    @Bean
    public WebSocketHandlerAdapter webSocketHandlerAdapter() {
        return new WebSocketHandlerAdapter();
    }

    /**
     * 映射路径
     * @param echo
     * @param dateTimeHandler
     * @return
     */
    @Bean
    public HandlerMapping webSocketMapping(final EchoHandler echo, final DateTimeHandler dateTimeHandler,
                                           final UserHandler userHandler) {
        final Map<String, WebSocketHandler> mappings = Maps.newHashMap();
        mappings.put("/echo", echo);
        mappings.put("/time", dateTimeHandler);
        mappings.put("/usr", userHandler);

        final SimpleUrlHandlerMapping handlerMapping = new SimpleUrlHandlerMapping();
        handlerMapping.setOrder(Ordered.HIGHEST_PRECEDENCE);
        handlerMapping.setUrlMap(mappings);
        return handlerMapping;
    }

}
